﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

namespace Edu.ZJ
{
    public static class AccountUtil
    {
        private static JObject obj;
        static AccountUtil()
        {
            Init();
        }

        public static void Update(List<AccountModel> list)
        {
            foreach (var item in list)
            {
                if (obj.ContainsKey(item.Code))
                {
                    var token = obj[item.Code];
                    if (token != null)
                    {
                        token["Account"] = item.Account;
                        token["Password"] = item.Password;
                    }
                }
            }

            FileUtil.WriteFileContent(StringUtil.ToJson(obj), "account", "account.json");
            SiteUtil.Update(list);
        }

        public static List<AccountModel> GetAccountList()
        {
            var list = SiteUtil.GetSiteList();

            int no = 0;
            return list.Select(m => new AccountModel()
            {
                No = ++no,
                Code = m.Code,
                Name = m.Name,
                Domain = m.Domain,
                Account = m.User.Account,
                Password = m.User.Password
            }).ToList();
        }

        public static UserModel GetUserByCode(string code)
        {
            UserModel user = null;
            if (obj.ContainsKey(code))
            {
                user = obj.GetValue(code).ToObject<UserModel>();
            }
            if (user == null)
            {
                user = new UserModel();
            }
            return user;
        }

        private static void Init()
        {
            string json = FileUtil.GetFileContent("account", "account.json");
            if (!string.IsNullOrEmpty(json))
            {
                obj = StringUtil.Parse<JObject>(json);
            }
            if (obj == null)
            {
                obj = new JObject();
            }
        }
    }
}
